"use client"

import { useState, useEffect, useRef } from 'react'
import { textStyles, fontSizes, fontWeights } from '../../lib/fontConfig'
// 教学提醒组件已移除
import { useProgressManager } from '../../lib/progressManager'
import { FindCharGame } from './games/FindCharGame'
import { QuizGame } from './games/QuizGame'
import { MemoryCardGame } from './games/MemoryCardGame'
import { ConnectGame } from './games/ConnectGame'
import { QuickRecognitionGame } from './games/QuickRecognitionGame'
import { JigsawPuzzleGame } from './games/JigsawPuzzleGame'
import { EliminationGame } from './games/EliminationGame'
import { ShootingGame } from './games/ShootingGame'

interface Course {
  lesson_number: string
  course_name: string
  target_char: string
}

interface GameConsolidationDisplayProps {
  currentCourse?: Course
}



// 游戏类型定义
interface GameType {
  id: string
  name: string
  icon: string
  description: string
  difficulty: 'easy' | 'medium' | 'hard'
  requiredLessons: number
  isUnlocked: boolean
  color: string
}

// 游戏状态
interface GameState {
  currentGame: string | null
  isPlaying: boolean
  score: number
  level: number
  timeLeft: number
  lives: number
  correctAnswers: number
  totalQuestions: number
  gameData: any
}

// 汉字数据接口
interface CharacterData {
  character: string
  pinyin: string
  meaning: string
  lesson: number
  strokes: number
  radicals: string[]
  words: string[]
}

export function GameConsolidationDisplay({ currentCourse }: GameConsolidationDisplayProps) {
  const { 
    getLearnedCharacters, 
    generateSmartContent, 
    updateCharacterProgress,
    getLearningStats
  } = useProgressManager()
  const [gameCharacters, setGameCharacters] = useState<string[]>([])

  const [gameState, setGameState] = useState<GameState>({
    currentGame: null,
    isPlaying: false,
    score: 0,
    level: 1,
    timeLeft: 60,
    lives: 3,
    correctAnswers: 0,
    totalQuestions: 0,
    gameData: null
  })

  // 管理功能已移至后台管理系统
  
  // 随机游戏轮转状态
  const [isSpinning, setIsSpinning] = useState(false)
  const [currentSpinGame, setCurrentSpinGame] = useState('')
  const [spinSpeed, setSpinSpeed] = useState(100)

  // 游戏类型配置
  const gameTypes: GameType[] = [
    {
      id: 'memory',
      name: '汉字记忆卡',
      icon: '🧠',
      description: '翻转卡片，配对汉字和含义',
      difficulty: 'easy',
      requiredLessons: 1,
      isUnlocked: true,
      color: 'from-blue-400 to-blue-500'
    },
    {
      id: 'quiz',
      name: '汉字闯关题',
      icon: '🎯',
      description: '回答汉字相关的选择题',
      difficulty: 'medium',
      requiredLessons: 2,
      isUnlocked: true,
      color: 'from-green-400 to-green-500'
    },
    {
      id: 'snake',
      name: '汉字贪吃蛇',
      icon: '🐍',
      description: '控制蛇吃正确的汉字',
      difficulty: 'medium',
      requiredLessons: 3,
      isUnlocked: true,
      color: 'from-purple-400 to-purple-500'
    },
    {
      id: 'match',
      name: '汉字连线',
      icon: '🔗',
      description: '连接相关的汉字和词语',
      difficulty: 'medium',
      requiredLessons: 3,
      isUnlocked: true,
      color: 'from-orange-400 to-orange-500'
    },
    {
      id: 'elimination',
      name: '汉字消消乐',
      icon: '💥',
      description: '消除相同的汉字获得分数',
      difficulty: 'hard',
      requiredLessons: 4,
      isUnlocked: true,
      color: 'from-pink-400 to-pink-500'
    },
    {
      id: 'typing',
      name: '汉字打字',
      icon: '⌨️',
      description: '根据拼音快速输入汉字',
      difficulty: 'hard',
      requiredLessons: 5,
      isUnlocked: false,
      color: 'from-cyan-400 to-cyan-500'
    },
    {
      id: 'puzzle',
      name: '汉字拼图',
      icon: '🧩',
      description: '拼接汉字的偏旁部首',
      difficulty: 'hard',
      requiredLessons: 6,
      isUnlocked: false,
      color: 'from-indigo-400 to-indigo-500'
    },
    {
      id: 'rhythm',
      name: '汉字节拍',
      icon: '🎵',
      description: '跟着节拍读出汉字',
      difficulty: 'medium',
      requiredLessons: 4,
      isUnlocked: false,
      color: 'from-yellow-400 to-yellow-500'
    }
  ]

  // 智能汉字数据库（基于进度管理）
  const getAvailableCharacters = (): CharacterData[] => {
    const allCharacters: CharacterData[] = [
      { character: '木', pinyin: 'mù', meaning: '树木', lesson: 1, strokes: 4, radicals: ['木'], words: ['树木', '木头'] },
      { character: '人', pinyin: 'rén', meaning: '人类', lesson: 1, strokes: 2, radicals: ['人'], words: ['人类', '大人'] },
      { character: '口', pinyin: 'kǒu', meaning: '嘴巴', lesson: 1, strokes: 3, radicals: ['口'], words: ['口水', '开口'] },
      { character: '水', pinyin: 'shuǐ', meaning: '水流', lesson: 2, strokes: 4, radicals: ['水'], words: ['水流', '喝水'] },
      { character: '火', pinyin: 'huǒ', meaning: '火焰', lesson: 2, strokes: 4, radicals: ['火'], words: ['火焰', '生火'] },
      { character: '土', pinyin: 'tǔ', meaning: '土地', lesson: 2, strokes: 3, radicals: ['土'], words: ['土地', '泥土'] },
      { character: '山', pinyin: 'shān', meaning: '山峰', lesson: 3, strokes: 3, radicals: ['山'], words: ['山峰', '高山'] },
      { character: '石', pinyin: 'shí', meaning: '石头', lesson: 3, strokes: 5, radicals: ['石'], words: ['石头', '岩石'] },
      // 新增汉字用于测试智能内容生成
      { character: '林', pinyin: 'lín', meaning: '森林', lesson: 4, strokes: 8, radicals: ['木'], words: ['森林', '树林'] },
      { character: '森', pinyin: 'sēn', meaning: '茂密', lesson: 4, strokes: 12, radicals: ['木'], words: ['森林', '森严'] },
      { character: '河', pinyin: 'hé', meaning: '河流', lesson: 4, strokes: 8, radicals: ['氵'], words: ['河流', '河水'] },
      { character: '海', pinyin: 'hǎi', meaning: '大海', lesson: 5, strokes: 10, radicals: ['氵'], words: ['大海', '海水'] }
    ]

    // 使用智能内容生成，按照70%已学30%新学的比例
    const allChars = allCharacters.map(char => char.character)
    const smartContent = generateSmartContent(allChars, 8, { 
      knownContentRatio: 0.7, 
      newContentRatio: 0.3, 
      difficultyLevel: 'medium' 
    })

    // 更新游戏汉字列表用于提醒
    setGameCharacters(smartContent.contentMix)

    // 返回智能选择的汉字数据
    return allCharacters.filter(char => smartContent.contentMix.includes(char.character))
  }

  // 开始游戏
  const startGame = (gameId: string) => {
    const game = gameTypes.find(g => g.id === gameId)
    if (!game || !game.isUnlocked) return

    setGameState({
      currentGame: gameId,
      isPlaying: true,
      score: 0,
      level: 1,
      timeLeft: 60,
      lives: 3,
      correctAnswers: 0,
      totalQuestions: 0,
      gameData: initializeGameData(gameId)
    })

    // 播放开始音效（模拟）
    playSound('start')
  }

  // 初始化游戏数据
  const initializeGameData = (gameId: string) => {
    const availableChars = getAvailableCharacters()
    
    switch (gameId) {
      case 'memory':
        return {
          cards: generateMemoryCards(availableChars.slice(0, 6)),
          flippedCards: [],
          matchedPairs: 0
        }
      case 'quiz':
        return {
          questions: generateQuizQuestions(availableChars),
          currentQuestion: 0,
          selectedAnswer: null
        }
      case 'snake':
        return {
          snake: [{ x: 10, y: 10 }],
          food: { x: 15, y: 15, character: availableChars[0].character },
          direction: 'right',
          targetCharacters: availableChars.slice(0, 5)
        }
      case 'elimination':
        return {
          grid: generateEliminationGrid(availableChars),
          selectedCells: [],
          combo: 0
        }
      default:
        return {}
    }
  }

  // 生成记忆卡片
  const generateMemoryCards = (characters: CharacterData[]) => {
    const cards: any[] = []
    characters.forEach((char, index) => {
      cards.push({ id: `char-${index}`, type: 'character', content: char.character, isFlipped: false, isMatched: false })
      cards.push({ id: `meaning-${index}`, type: 'meaning', content: char.meaning, isFlipped: false, isMatched: false })
    })
    return cards.sort(() => Math.random() - 0.5)
  }

  // 生成选择题
  const generateQuizQuestions = (characters: CharacterData[]) => {
    return characters.slice(0, 5).map((char, index) => ({
      id: index,
      question: `"${char.character}"的读音是？`,
      options: [char.pinyin, 'wú', 'bù', 'shì'].sort(() => Math.random() - 0.5),
      correctAnswer: char.pinyin,
      explanation: `"${char.character}"读作"${char.pinyin}"，意思是${char.meaning}。`
    }))
  }

  // 生成消消乐网格
  const generateEliminationGrid = (characters: CharacterData[]) => {
    const grid = []
    const chars = characters.slice(0, 4).map(c => c.character)
    
    for (let i = 0; i < 8; i++) {
      const row = []
      for (let j = 0; j < 8; j++) {
        row.push({
          character: chars[Math.floor(Math.random() * chars.length)],
          x: j,
          y: i,
          isSelected: false,
          isMatched: false
        })
      }
      grid.push(row)
    }
    return grid
  }

  // 播放音效（模拟）
  const playSound = (type: 'start' | 'correct' | 'wrong' | 'complete' | 'click') => {
    // 这里可以集成真实的音效播放
    console.log(`播放音效: ${type}`)
  }

  // 播放特效（模拟）
  const playEffect = (type: 'sparkle' | 'explosion' | 'rainbow' | 'star') => {
    // 这里可以集成真实的视觉特效
    console.log(`播放特效: ${type}`)
  }

  // 结束游戏
  const endGame = () => {
    setGameState(prev => ({ ...prev, isPlaying: false }))

    // 更新学习进度 - 根据游戏表现更新汉字掌握度
    const correctRate = gameState.totalQuestions > 0 ? gameState.correctAnswers / gameState.totalQuestions : 0
    gameCharacters.forEach(char => {
      // 假设答对率超过70%算正确
      const isCorrect = correctRate >= 0.7
      updateCharacterProgress(char, isCorrect)
    })

    playSound('complete')
    playEffect('rainbow')
  }

  // 重置游戏
  const resetGame = () => {
    setGameState({
      currentGame: null,
      isPlaying: false,
      score: 0,
      level: 1,
      timeLeft: 60,
      lives: 3,
      correctAnswers: 0,
      totalQuestions: 0,
      gameData: null
    })
  }

  // 随机游戏轮转逻辑
  const startGameSpin = () => {
    const games = [
      { id: 'word-puzzle', name: '成语缺字', icon: '🧩' },
      { id: 'find-char', name: '汉字找茬', icon: '🔍' },
      { id: 'quiz', name: '知识问答', icon: '❓' },
      { id: 'jigsaw', name: '汉字拼图', icon: '🧩' },
      { id: 'connect', name: '汉字连线', icon: '🔗' },
      { id: 'memory', name: '汉字记忆', icon: '🧠' },
      { id: 'classify', name: '汉字分类', icon: '📁' }
    ]

    setIsSpinning(true)
    
    let currentIndex = 0
    const maxSpins = 25 + Math.floor(Math.random() * 15) // 随机转25-40次

    // 递归轮转函数，实现逐渐减速效果
    const spinWithDeceleration = (count: number, speed: number) => {
      if (count >= maxSpins) {
        // 轮转结束，选择最终游戏
        const finalGame = games[Math.floor(Math.random() * games.length)]
        setCurrentSpinGame(finalGame.name)
        
        // 延迟一下再开始游戏，让用户看清结果
        setTimeout(() => {
          setIsSpinning(false)
          setGameState(prev => ({ ...prev, currentGame: finalGame.id, isPlaying: true }))
          startGame(finalGame.id)
        }, 1500)
        return
      }

      // 显示当前游戏名
      setCurrentSpinGame(games[currentIndex].name)
      currentIndex = (currentIndex + 1) % games.length

      // 计算新速度 - 逐渐减速
      let newSpeed = speed
      const progress = count / maxSpins
      
      if (progress > 0.8) {
        newSpeed += 50 // 最后阶段大幅减速
      } else if (progress > 0.6) {
        newSpeed += 25 // 后期减速
      } else if (progress > 0.3) {
        newSpeed += 10 // 中期开始减速
      } else {
        newSpeed += 2  // 前期轻微加速
      }

      // 继续下一次轮转
      setTimeout(() => {
        spinWithDeceleration(count + 1, newSpeed)
      }, newSpeed)
    }

    // 开始轮转
    spinWithDeceleration(0, 80)
  }

  // 渲染进度面板


  // 渲染游戏选择界面
  const renderGameSelection = () => (
    <div className="grid grid-cols-2 gap-4">
      {gameTypes.map((game) => (
        <div
          key={game.id}
          className={`
            bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border 
            transition-all duration-300 hover:shadow-xl
            ${game.isUnlocked 
              ? 'border-green-100 hover:scale-105 cursor-pointer' 
              : 'border-gray-200 opacity-50 cursor-not-allowed'
            }
          `}
          onClick={() => game.isUnlocked && startGame(game.id)}
        >
          <div className="text-center">
            <div className="text-4xl mb-2">{game.icon}</div>
            <h3 className={`${textStyles.tag} mb-2 font-bold ${
              game.isUnlocked ? 'text-gray-800' : 'text-gray-400'
            }`}>
              {game.name}
            </h3>
            <p className={`${textStyles.caption} mb-3 ${
              game.isUnlocked ? 'text-gray-600' : 'text-gray-400'
            }`}>
              {game.description}
            </p>
            
            {/* 难度和要求 */}
            <div className="flex justify-between items-center text-xs">
              <span className={`px-2 py-1 rounded-full ${
                game.difficulty === 'easy' ? 'bg-green-100 text-green-700' :
                game.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-700' :
                'bg-red-100 text-red-700'
              }`}>
                {game.difficulty === 'easy' ? '简单' : 
                 game.difficulty === 'medium' ? '中等' : '困难'}
              </span>
              <span className="text-gray-500">
                需要第{game.requiredLessons}课
              </span>
            </div>

            {!game.isUnlocked && (
              <div className="mt-2 text-xs text-red-500">
                🔒 需要完成第{game.requiredLessons}课解锁
              </div>
            )}
          </div>
        </div>
      ))}
    </div>
  )

  // 管理功能已移至后台管理系统

  // 渲染汉字拼图游戏
  const renderJigsawGame = () => (
    <div className="h-full flex items-center justify-center">
      <div className="text-center">
        <div className="text-6xl mb-4">🧩</div>
        <h3 className={`${textStyles.sectionTitle} text-purple-700 mb-2`}>
          汉字拼图
        </h3>
        <p className={`${textStyles.description} text-gray-600`}>
          人靠在树下 → 休
        </p>
        <div className="mt-6 bg-white/90 backdrop-blur-sm rounded-xl p-6 max-w-md mx-auto">
          <div className="text-4xl mb-4">休</div>
          <div className="grid grid-cols-3 gap-2">
            <div className="w-16 h-16 bg-gray-200 rounded border-2 border-dashed border-gray-400"></div>
            <div className="w-16 h-16 bg-gray-200 rounded border-2 border-dashed border-gray-400"></div>
            <div className="w-16 h-16 bg-gray-200 rounded border-2 border-dashed border-gray-400"></div>
          </div>
        </div>
      </div>
    </div>
  )

  // 渲染汉字连线游戏
  const renderConnectGame = () => (
    <div className="h-full flex items-center justify-center">
      <div className="text-center">
        <div className="text-6xl mb-4">🔗</div>
        <h3 className={`${textStyles.sectionTitle} text-cyan-700 mb-2`}>
          汉字连线
        </h3>
        <p className={`${textStyles.description} text-gray-600`}>
          连接汉字和拼音
        </p>
        <div className="mt-6 bg-white/90 backdrop-blur-sm rounded-xl p-6 max-w-md mx-auto">
          <div className="grid grid-cols-2 gap-8">
            <div className="space-y-3">
              <div className="text-2xl bg-blue-100 p-3 rounded">木</div>
              <div className="text-2xl bg-blue-100 p-3 rounded">林</div>
              <div className="text-2xl bg-blue-100 p-3 rounded">森</div>
            </div>
            <div className="space-y-3">
              <div className="text-lg bg-green-100 p-3 rounded">mù</div>
              <div className="text-lg bg-green-100 p-3 rounded">lín</div>
              <div className="text-lg bg-green-100 p-3 rounded">sēn</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )

  // 渲染汉字分类游戏
  const renderClassifyGame = () => (
    <div className="h-full flex items-center justify-center">
      <div className="text-center">
        <div className="text-6xl mb-4">📁</div>
        <h3 className={`${textStyles.sectionTitle} text-orange-700 mb-2`}>
          汉字分类
        </h3>
        <p className={`${textStyles.description} text-gray-600`}>
          将汉字拖拽到正确的分类中
        </p>
        <div className="mt-6 bg-white/90 backdrop-blur-sm rounded-xl p-6 max-w-2xl mx-auto">
          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="bg-yellow-100 p-4 rounded-xl">
              <h4 className="font-bold text-yellow-800 mb-2">木字旁</h4>
              <div className="h-20 border-2 border-dashed border-yellow-400 rounded"></div>
            </div>
            <div className="bg-blue-100 p-4 rounded-xl">
              <h4 className="font-bold text-blue-800 mb-2">三点水</h4>
              <div className="h-20 border-2 border-dashed border-blue-400 rounded"></div>
            </div>
            <div className="bg-red-100 p-4 rounded-xl">
              <h4 className="font-bold text-red-800 mb-2">火字旁</h4>
              <div className="h-20 border-2 border-dashed border-red-400 rounded"></div>
            </div>
          </div>
          <div className="flex justify-center space-x-3">
            <div className="w-12 h-12 bg-white border-2 border-gray-300 rounded flex items-center justify-center text-lg font-bold">树</div>
            <div className="w-12 h-12 bg-white border-2 border-gray-300 rounded flex items-center justify-center text-lg font-bold">河</div>
            <div className="w-12 h-12 bg-white border-2 border-gray-300 rounded flex items-center justify-center text-lg font-bold">烧</div>
            <div className="w-12 h-12 bg-white border-2 border-gray-300 rounded flex items-center justify-center text-lg font-bold">林</div>
            <div className="w-12 h-12 bg-white border-2 border-gray-300 rounded flex items-center justify-center text-lg font-bold">海</div>
            <div className="w-12 h-12 bg-white border-2 border-gray-300 rounded flex items-center justify-center text-lg font-bold">灯</div>
          </div>
        </div>
      </div>
    </div>
  )

  // 渲染成语缺字游戏
  const renderWordPuzzleGame = () => (
    <div className="h-full flex items-center justify-center">
      <div className="text-center">
        <div className="text-6xl mb-4">🧩</div>
        <h3 className={`${textStyles.sectionTitle} text-green-700 mb-2`}>
          成语缺字
        </h3>
        <p className={`${textStyles.description} text-gray-600`}>
          "木"可以分成三部分进行处理
        </p>
        <div className="mt-6 bg-white/90 backdrop-blur-sm rounded-xl p-6 max-w-md mx-auto">
          <div className="grid grid-cols-4 gap-3 mb-6">
            <div className="w-16 h-16 bg-gray-100 border-2 border-gray-300 rounded flex items-center justify-center text-2xl font-bold">一</div>
            <div className="w-16 h-16 bg-gray-100 border-2 border-gray-300 rounded flex items-center justify-center text-2xl font-bold">?</div>
            <div className="w-16 h-16 bg-gray-100 border-2 border-gray-300 rounded flex items-center justify-center text-2xl font-bold">三</div>
            <div className="w-16 h-16 bg-gray-100 border-2 border-gray-300 rounded flex items-center justify-center text-2xl font-bold">分</div>
          </div>
          <div className="grid grid-cols-4 gap-3">
            <div className="w-16 h-16 bg-blue-100 border-2 border-blue-300 rounded flex items-center justify-center text-2xl font-bold cursor-pointer hover:bg-blue-200">木</div>
            <div className="w-16 h-16 bg-blue-100 border-2 border-blue-300 rounded flex items-center justify-center text-2xl font-bold cursor-pointer hover:bg-blue-200">火</div>
            <div className="w-16 h-16 bg-blue-100 border-2 border-blue-300 rounded flex items-center justify-center text-2xl font-bold cursor-pointer hover:bg-blue-200">水</div>
            <div className="w-16 h-16 bg-blue-100 border-2 border-blue-300 rounded flex items-center justify-center text-2xl font-bold cursor-pointer hover:bg-blue-200">土</div>
          </div>
        </div>
      </div>
    </div>
  )

  // 渲染简单的记忆游戏
  const renderMemoryGame = () => {
    const { cards } = gameState.gameData
    
    return (
      <div className="space-y-4">
        <div className="text-center">
          <h3 className={`${textStyles.sectionTitle} text-blue-700 font-bold mb-2`}>
            🧠 汉字记忆卡
          </h3>
          <p className={`${textStyles.description} text-gray-600`}>
            翻转卡片，找到汉字和含义的配对
          </p>
        </div>
        
        <div className="grid grid-cols-4 gap-3">
          {cards.map((card: any) => (
            <div
              key={card.id}
              onClick={() => {
                if (!card.isFlipped && !card.isMatched) {
                  playSound('click')
                  // 这里添加翻卡逻辑
                }
              }}
              className={`
                w-16 h-16 rounded-lg cursor-pointer transition-all duration-300
                flex items-center justify-center text-center
                ${card.isFlipped || card.isMatched
                  ? card.type === 'character'
                    ? 'bg-blue-100 border-2 border-blue-400'
                    : 'bg-green-100 border-2 border-green-400'
                  : 'bg-gray-200 border-2 border-gray-300 hover:bg-gray-300'
                }
                ${card.isMatched ? 'opacity-50' : ''}
              `}
            >
              {card.isFlipped || card.isMatched ? (
                <div className={`${textStyles.caption} font-bold`}>
                  {card.content}
                </div>
              ) : (
                <div className="text-xl">❓</div>
              )}
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col p-3 space-y-4">
      {/* 标题区域 */}
      <div className="text-center">
        <h2 className={`${textStyles.mainTitle} text-purple-700 mb-2 drop-shadow-sm`}>
          🎮 游戏巩固
        </h2>
        <p className={`${textStyles.description} text-gray-600`}>
          通过趣味游戏巩固学习成果，让学习更有趣！
        </p>
      </div>

      {/* 游戏状态栏 */}
      {gameState.isPlaying && (
        <div className="bg-white/90 backdrop-blur-sm rounded-xl p-3 shadow-lg border border-purple-100">
          <div className="flex justify-between items-center">
            <div className="flex space-x-6">
              <div className="text-center">
                <div className={`${textStyles.tag} text-blue-700 font-bold`}>
                  {gameState.score}
                </div>
                <div className={`${textStyles.caption} text-gray-600`}>分数</div>
              </div>
              <div className="text-center">
                <div className={`${textStyles.tag} text-green-700 font-bold`}>
                  {gameState.correctAnswers}
                </div>
                <div className={`${textStyles.caption} text-gray-600`}>正确</div>
              </div>
              <div className="text-center">
                <div className={`${textStyles.tag} text-red-700 font-bold`}>
                  {gameState.lives}
                </div>
                <div className={`${textStyles.caption} text-gray-600`}>生命</div>
              </div>
              <div className="text-center">
                <div className={`${textStyles.tag} text-orange-700 font-bold`}>
                  {gameState.timeLeft}s
                </div>
                <div className={`${textStyles.caption} text-gray-600`}>时间</div>
              </div>
            </div>
            <button
              onClick={resetGame}
              className={`
                ${textStyles.secondaryButton} px-4 py-2 
                bg-red-500 text-white rounded-lg
                hover:bg-red-600 hover:scale-105 
                transition-all duration-300
              `}
            >
              🏠 退出游戏
            </button>
          </div>
        </div>
      )}

      {/* 直播区域 - 16:9比例 */}
      <div className="flex-1 flex items-center justify-center p-4">
        <div className="w-full max-w-6xl">
          <div 
            className="relative w-full bg-white rounded-2xl shadow-lg overflow-hidden"
            style={{ paddingBottom: '56.25%' }} // 16:9 aspect ratio
          >
            <div className="absolute inset-0 flex items-center justify-center">
              {gameState.currentGame && gameState.isPlaying ? (
                <div className="w-full h-full">
                  {/* 字根记忆翻牌 */}
                  {gameState.currentGame === 'memory' && (
                    <MemoryCardGame 
                      targetChar={currentCourse?.target_char || '木'}
                      onGameEnd={(score, correct, total) => {
                        setGameState(prev => ({
                          ...prev,
                          score: score,
                          correctAnswers: correct,
                          totalQuestions: total,
                          isPlaying: false
                        }))
                        endGame()
                      }}
                    />
                  )}
                  
                  {/* 汉字连连看 */}
                  {gameState.currentGame === 'connect' && (
                    <ConnectGame 
                      targetChar={currentCourse?.target_char || '木'}
                      onGameEnd={(score, correct, total) => {
                        setGameState(prev => ({
                          ...prev,
                          score: score,
                          correctAnswers: correct,
                          totalQuestions: total,
                          isPlaying: false
                        }))
                        endGame()
                      }}
                    />
                  )}
                  
                  {/* 快速识字挑战 */}
                  {gameState.currentGame === 'quiz' && (
                    <QuickRecognitionGame 
                      targetChar={currentCourse?.target_char || '木'}
                      onGameEnd={(score, correct, total) => {
                        setGameState(prev => ({
                          ...prev,
                          score: score,
                          correctAnswers: correct,
                          totalQuestions: total,
                          isPlaying: false
                        }))
                        endGame()
                      }}
                    />
                  )}
                  
                  {/* 字根拼图 */}
                  {gameState.currentGame === 'jigsaw' && (
                    <JigsawPuzzleGame 
                      targetChar={currentCourse?.target_char || '木'}
                      onGameEnd={(score, correct, total) => {
                        setGameState(prev => ({
                          ...prev,
                          score: score,
                          correctAnswers: correct,
                          totalQuestions: total,
                          isPlaying: false
                        }))
                        endGame()
                      }}
                    />
                  )}
                  
                  {/* 汉字消除 */}
                  {gameState.currentGame === 'elimination' && (
                    <EliminationGame 
                      targetChar={currentCourse?.target_char || '木'}
                      onGameEnd={(score, correct, total) => {
                        setGameState(prev => ({
                          ...prev,
                          score: score,
                          correctAnswers: correct,
                          totalQuestions: total,
                          isPlaying: false
                        }))
                        endGame()
                      }}
                    />
                  )}
                  
                  {/* 字根射击 */}
                  {gameState.currentGame === 'shooting' && (
                    <ShootingGame 
                      targetChar={currentCourse?.target_char || '木'}
                      onGameEnd={(score, correct, total) => {
                        setGameState(prev => ({
                          ...prev,
                          score: score,
                          correctAnswers: correct,
                          totalQuestions: total,
                          isPlaying: false
                        }))
                        endGame()
                      }}
                    />
                  )}
                  
                  {/* 保留原有游戏 */}
                  {gameState.currentGame === 'find-char' && (
                    <FindCharGame 
                      targetChar={currentCourse?.target_char || '木'}
                      onGameEnd={(score, correct, total) => {
                        setGameState(prev => ({
                          ...prev,
                          score: score,
                          correctAnswers: correct,
                          totalQuestions: total,
                          isPlaying: false
                        }))
                        endGame()
                      }}
                    />
                  )}
                  
                  {/* 其他游戏保持原样 */}
                  {gameState.currentGame === 'classify' && renderClassifyGame()}
                  {gameState.currentGame === 'word-puzzle' && renderWordPuzzleGame()}
                </div>
              ) : (
                // 游戏选择界面 - 直接在直播区展示
                <div className="w-full h-full p-8 bg-gradient-to-br from-purple-50 via-pink-50 to-blue-50">
                  {/* 标题区域 */}
                  <div className="text-center mb-8">
                    <div className="text-6xl mb-4 animate-bounce">🎮</div>
                    <h2 className="text-3xl font-bold text-purple-700 mb-2">
                      🎯 选择你喜欢的游戏
                    </h2>
                    <p className="text-lg text-gray-600">
                      通过趣味游戏巩固学习成果，让学习更有趣！
                    </p>
                  </div>

                  {/* 游戏网格 */}
                  <div className="grid grid-cols-4 gap-6 max-w-4xl mx-auto">
                    {/* 第一排 - 参考用户截图的6种游戏 */}
                    <button
                      onClick={() => {
                        setGameState(prev => ({ ...prev, currentGame: 'memory', isPlaying: true }))
                        startGame('memory')
                      }}
                      className="group bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-white/60 
                               hover:shadow-xl hover:scale-105 transition-all duration-300 transform hover:-translate-y-2"
                    >
                      <div className="text-center">
                        <div className="text-5xl mb-3 group-hover:animate-bounce">🧠</div>
                        <h3 className="text-lg font-bold text-gray-800 mb-2">字根记忆翻牌</h3>
                        <p className="text-sm text-gray-600">翻开卡片，记住字根位置，找到翻牌</p>
                        <div className="mt-3 px-3 py-1 bg-pink-100 text-pink-700 rounded-full text-xs">简单</div>
                      </div>
                    </button>

                    <button
                      onClick={() => {
                        setGameState(prev => ({ ...prev, currentGame: 'connect', isPlaying: true }))
                        startGame('connect')
                      }}
                      className="group bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-white/60 
                               hover:shadow-xl hover:scale-105 transition-all duration-300 transform hover:-translate-y-2"
                    >
                      <div className="text-center">
                        <div className="text-5xl mb-3 group-hover:animate-bounce">🔗</div>
                        <h3 className="text-lg font-bold text-gray-800 mb-2">汉字连连看</h3>
                        <p className="text-sm text-gray-600">连连看、快速识字</p>
                        <div className="mt-3 px-3 py-1 bg-cyan-100 text-cyan-700 rounded-full text-xs">中等</div>
                      </div>
                    </button>

                    <button
                      onClick={() => {
                        setGameState(prev => ({ ...prev, currentGame: 'quiz', isPlaying: true }))
                        startGame('quiz')
                      }}
                      className="group bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-white/60 
                               hover:shadow-xl hover:scale-105 transition-all duration-300 transform hover:-translate-y-2"
                    >
                      <div className="text-center">
                        <div className="text-5xl mb-3 group-hover:animate-bounce">⚡</div>
                        <h3 className="text-lg font-bold text-gray-800 mb-2">快速识字挑战</h3>
                        <p className="text-sm text-gray-600">考验反应，快速识字</p>
                        <div className="mt-3 px-3 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs">中等</div>
                      </div>
                    </button>

                    {/* 第二排 */}
                    <button
                      onClick={() => {
                        setGameState(prev => ({ ...prev, currentGame: 'jigsaw', isPlaying: true }))
                        startGame('jigsaw')
                      }}
                      className="group bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-white/60 
                               hover:shadow-xl hover:scale-105 transition-all duration-300 transform hover:-translate-y-2"
                    >
                      <div className="text-center">
                        <div className="text-5xl mb-3 group-hover:animate-bounce">🧩</div>
                        <h3 className="text-lg font-bold text-gray-800 mb-2">字根拼图</h3>
                        <p className="text-sm text-gray-600">将分散的字根拖拽组合成完整汉字</p>
                        <div className="mt-3 px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-xs">困难</div>
                      </div>
                    </button>

                    <button
                      onClick={() => {
                        setGameState(prev => ({ ...prev, currentGame: 'elimination', isPlaying: true }))
                        startGame('elimination')
                      }}
                      className="group bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-white/60 
                               hover:shadow-xl hover:scale-105 transition-all duration-300 transform hover:-translate-y-2"
                    >
                      <div className="text-center">
                        <div className="text-5xl mb-3 group-hover:animate-bounce">💥</div>
                        <h3 className="text-lg font-bold text-gray-800 mb-2">汉字消除</h3>
                        <p className="text-sm text-gray-600">点击相同字根组成的汉字进行消除</p>
                        <div className="mt-3 px-3 py-1 bg-red-100 text-red-700 rounded-full text-xs">困难</div>
                      </div>
                    </button>

                    <button
                      onClick={() => {
                        setGameState(prev => ({ ...prev, currentGame: 'shooting', isPlaying: true }))
                        startGame('shooting')
                      }}
                      className="group bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-white/60 
                               hover:shadow-xl hover:scale-105 transition-all duration-300 transform hover:-translate-y-2"
                    >
                      <div className="text-center">
                        <div className="text-5xl mb-3 group-hover:animate-bounce">🎯</div>
                        <h3 className="text-lg font-bold text-gray-800 mb-2">字根射击</h3>
                        <p className="text-sm text-gray-600">射击正确的字根组成目标汉字</p>
                        <div className="mt-3 px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-xs">困难</div>
                      </div>
                    </button>

                    {/* 随机游戏按钮 */}
                    <button
                      onClick={startGameSpin}
                      disabled={isSpinning}
                      className={`group rounded-2xl p-6 shadow-lg transition-all duration-300 transform
                        ${isSpinning 
                          ? 'bg-gradient-to-br from-yellow-400 via-orange-400 to-red-400 scale-110 shadow-2xl' 
                          : 'bg-gradient-to-br from-pink-400 via-purple-400 to-indigo-400 hover:shadow-xl hover:scale-105 hover:-translate-y-2'
                        } text-white`}
                    >
                      <div className="text-center">
                        <div className={`text-5xl mb-3 ${isSpinning ? 'animate-spin' : 'group-hover:animate-bounce'}`}>
                          {isSpinning ? '🎰' : '🎲'}
                        </div>
                        
                        {isSpinning ? (
                          <>
                            <h3 className="text-lg font-bold mb-2 animate-pulse">正在抽取...</h3>
                            <p className="text-sm opacity-90 font-bold text-yellow-100 animate-bounce">
                              {currentSpinGame || '准备中...'}
                            </p>
                            <div className="mt-3 px-3 py-1 bg-white/30 rounded-full text-xs animate-pulse">
                              轮转中
                            </div>
                          </>
                        ) : (
                          <>
                            <h3 className="text-lg font-bold mb-2">随机游戏</h3>
                            <p className="text-sm opacity-90">让我来选择一个游戏</p>
                            <div className="mt-3 px-3 py-1 bg-white/20 rounded-full text-xs">惊喜</div>
                          </>
                        )}
                      </div>
                    </button>
                  </div>

                  {/* 底部提示 */}
                  <div className="text-center mt-8">
                    <p className="text-sm text-gray-500">
                      💡 提示：点击任意游戏开始挑战，完成游戏可获得积分奖励！
                    </p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>



      {/* 教学提醒组件已移除 */}
    </div>
  )
} 